package sanduche.controllers;

import java.util.List;

import models.NotificationId;
import models.Persona;
import models.users.User;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Http.Session;
import sanduche.play.shared.ModuleConfig;
import sanduche.play.shared.RequestBody;
import sanduche.play.shared.RequestMethod;
import sanduche.play.shared.Route;
import sanduche.play.shared.UrlParam;
import services.DAO;
import services.PasswordHash;
import util.SessionObj;
import vos.LoginCredentials;
import enums.OSs;

@ModuleConfig(prefix = "/api")
public class UserController {
	public static final String SESSION_OBJ = "sessionObj";

	private static SessionObj getSessionObj(Session session) {
		return Json.fromJson(Json.parse(session.get(SESSION_OBJ)),
				SessionObj.class);
	}

	@Transactional(readOnly = true)
	@Route(value = "/login", method = RequestMethod.POST)
	public static void login(@RequestBody LoginCredentials c, Session session)
			throws Exception {

		User user = DAO.query(User.class, 1, "username", c.username);

		if (user == null
				|| !PasswordHash.validatePassword(c.password,
						user.getPassword()))
			throw new Exception("Usuario o contraseña incorrecto");

		SessionObj so = SessionObj.instantiate(user);
		session.put(SESSION_OBJ, so.toJson());

		// if (c.rememberMe) {
		// response().setCookie("remember", Crypto.sign(c.username));
		// response().setCookie("username", c.username);
		// }

	}

	@Transactional
	@Route(value = "/device/android/:idAndroid", method = RequestMethod.POST)
	public static void saveAndroidId(Session session,
			@UrlParam("idAndroid") String idAndroid) {
		System.out.println("guardado el ID: " + idAndroid);
		NotificationId ni = new NotificationId();
		ni.setOs(OSs.ANDROID);
		ni.setNotificationId(idAndroid);
		ni.setIdPersona(getSessionObj(session).getId());
		DAO.persist(ni);

	}

	@Transactional(readOnly = true)
	@Route(value = "/user/self", method = RequestMethod.POST)
	public static User getMyInfo(Session session) {
		Long userId = getSessionObj(session).getId();
		User u = DAO.find(User.class, userId);
		return u;
	}

	@Route(value = "/user/logout", method = RequestMethod.GET)
	public static void logout(Session session) {
		session.clear();
	}

	@Transactional
	@Route(value = "/persona/:documento", method = RequestMethod.GET, iteratedClass = Persona.class)
	public static List<Persona> getPersonasConDocumento(
			@UrlParam("documento") String documento) {
		List<Persona> personas = DAO.queryLike(Persona.class, 10, "documento",
				"%" + documento + "%");
		return personas;
	}

}
